package com.Iconcat.system.service.impl;

import com.Iconcat.system.entity.CatUser;
import com.Iconcat.system.mapper.CatMenuMapper;
import com.Iconcat.system.mapper.CatUserMapper;
import com.Iconcat.system.response.Result;
import com.Iconcat.system.service.CatUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Service
public class CatUserServiceImpl extends ServiceImpl<CatUserMapper,CatUser> implements CatUserService {

    @Resource
    private CatMenuMapper catMenuMapper;
    @Resource
    private  CatUserMapper catUserMapper;
    @Override
    public IPage<CatUser> userAll(Page<CatUser> page, QueryWrapper<CatUser> wrapper) {
        return this.baseMapper.userAll((com.baomidou.mybatisplus.extension.plugins.pagination.Page<CatUser>) page,wrapper);
    }

    @Override
    public boolean isUserExists(String phoneNumber) {
        return catMenuMapper.findByPhoneNumber(phoneNumber);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deductBalance(Integer userId, BigDecimal deductAmount,String paymentPassword) {
        // 查询用户当前余额
        CatUser user = getById(userId);
        if (user == null) {
            return Result.error().message("用户不存在");
        }
        // 校验支付密码
        String storedPaymentPassword = user.getPaymentPassword();
        if (!StringUtils.equals(paymentPassword, storedPaymentPassword)) {
            return Result.error().message("支付密码错误");
        }
        // 判断余额是否足够
        BigDecimal availableBalance = user.getAvailableBalance();
        if (availableBalance.compareTo(deductAmount) < 0) {
            return Result.error().message("余额不足");
        }

        // 扣除余额
        int rows = catUserMapper.updateBalance(userId, deductAmount);
        if (rows != 1) {
            // 扣除余额失败，可能是因为余额已经不足
            return Result.error().message("扣除余额失败");
        }

        return Result.ok().message("扣除成功");
    }

    @Override
    public void addBalance(Integer userId, BigDecimal totalEarnings) {
        CatUser user = catUserMapper.selectById(userId);
        if (user != null) {
            BigDecimal currentBalance = user.getAvailableBalance();
            user.setAvailableBalance(currentBalance.add(totalEarnings));
            catUserMapper.updateById(user);
        }
    }
    @Override
    public void clearTotalEarnings(Integer userId) {
        CatUser user = catUserMapper.selectById(userId);
        if (user != null) {
            user.setTotalEarnings(BigDecimal.ZERO);
            catUserMapper.updateById(user);
        }
    }

}
